from openai import OpenAI
import re
import core
import os
import json

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(SCRIPT_DIR, 'config.json')
MESSAGE_HISTORY_FILE = os.path.join(SCRIPT_DIR, 'message_history.json')

# 加载配置和历史记录
config = core.load_config(CONFIG_PATH)
API_MODEL = config['model']
API_NAME = config['name']
API_KEY = config['key']
API_URL = config['api_url']

# 初始化消息历史（从文件加载历史记录）
message_history = []
try:
    with open(MESSAGE_HISTORY_FILE, 'r', encoding='utf-8') as f:
        # 兼容旧格式和新格式
        loaded_data = json.load(f)
        if isinstance(loaded_data, dict):
            message_history = loaded_data.get('user', [])
        else:
            message_history = loaded_data
except FileNotFoundError:
    pass  # 保持空历史记录
except json.JSONDecodeError:
    print("消息历史文件格式错误，将使用空历史记录")
except Exception as e:
    print(f"加载历史记录失败: {e}")
    # 保留现有历史记录避免数据丢失

client = OpenAI(api_key=API_KEY, base_url=API_URL)

# 已移除多用户支持

def add_history(role, content):
    # 维护最大300条历史记录
    max_history = 300
    
    # 确保使用全局message_history
    global message_history
    
    # 添加新消息到内存（带调试日志）
    print(f"添加消息前历史记录数：{len(message_history)}")
    
    message_history.append({"role": role, "content": content})
    
    # 截断历史记录但保留最近300条
    if len(message_history) > max_history:
        message_history = message_history[-max_history:]
    #print(f"添加消息后历史记录数：{len(message_history)}")
    
    # 立即保存完整状态（带调试日志）
    try:
        with open(MESSAGE_HISTORY_FILE, 'w', encoding='utf-8') as f:
            json.dump(message_history, f, ensure_ascii=False, indent=2)
        #print("保存成功")
    except Exception as e:
        pass
        #print(f"保存聊天记录失败: {e}")

def clean_response(content):
    # 将<br><br>替换为换行符
    content = re.sub(r'<br>', '\n', content)
    return content.strip()

def reset_history():
    """重置对话历史（供前端调用）"""
    # 移除了user_name参数
    global message_history
    message_history = []
    try:
        with open(MESSAGE_HISTORY_FILE, 'w', encoding='utf-8') as f:
            json.dump(message_history, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"重置历史记录失败: {e}")

def chat(prompt):
    add_history("user", prompt)
    try:
        response = client.chat.completions.create(
            model=API_MODEL,
            messages=message_history
        )
        print(response)
        content = response.choices[0].message.content
        content = clean_response(content)
        add_history("assistant", content)
        return content
    except Exception as e:
        print(f"Error: {e}")
        return "抱歉，我遇到了一个错误，请稍后再试。"
